import { think } from "thinkjs";
import { IUser } from "../../types";
import mongo from '../../../../../utils/mongo';
import { SchemaUser } from '../../types/model/User';

class ImUserModel {

  /**
   * 根据account获取用户信息
   */
  async getUserByAccount({
    accounts,
    field
  }: {
    accounts: string[];
    field?: string;
  }): Promise<{
    users: IUser[];
    usersMap: { [propName: string]: IUser };
  }> {
    console.log('[getUserByAccount] ', accounts);
    const UserModel = mongo.model('user', SchemaUser);
    const users: IUser[] = await UserModel.find({
      account: { $in: accounts }
    });
    const usersMap = {};
    users.forEach(user => {
      usersMap[user.account] = user;
    });
    return {
      users,
      usersMap
    };
  }

  async findOneUser({
    account,
    field
  }: {
    account: string;
    field: string;
  }): Promise<{ user: IUser }> {
    const UserModel = mongo.model('user', SchemaUser);
    if (field) {
      const user: IUser = await UserModel.findOne({
        account
      }, field);
      return {
        user
      };
    } else {
      const user: IUser = await UserModel.findOne({
        account
      });
      return {
        user
      };
    }
  }

}

export default new ImUserModel();
